#include "stdafx.h"
#include "DesktopIcon.h"
// DesktopIconFetcher.cpp
#include <QDir>
#include <QFileInfo>
#include <QApplication>
#include <QStyle>

#ifdef Q_OS_WIN
#include <windows.h>
#include <shlobj.h>
#include <objbase.h>
#include <shobjidl.h>
#endif

DesktopIconFetcher::DesktopIconFetcher(QObject* parent)
    : QObject(parent)
{
}

QVector<DesktopIcon> DesktopIconFetcher::fetchDesktopIcons()
{
#ifdef Q_OS_WIN
    return fetchWindowsDesktopIcons();
#else
    // 其他平台的实现
    return QVector<DesktopIcon>();
#endif
}

#ifdef Q_OS_WIN
QVector<DesktopIcon> DesktopIconFetcher::fetchWindowsDesktopIcons()
{
    QVector<DesktopIcon> icons;

    // 获取桌面路径
    wchar_t desktopPath[MAX_PATH];
    if (SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, 0, desktopPath) != S_OK) {
        return icons;
    }

    // 遍历桌面文件
    QString desktopDir = QString::fromWCharArray(desktopPath);
    QDir dir(desktopDir);

    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    for (const QFileInfo& fileInfo : fileList) {
        DesktopIcon desktopIcon;
        desktopIcon.name = fileInfo.fileName();
        desktopIcon.filePath = fileInfo.absoluteFilePath();
        desktopIcon.isDirectory = fileInfo.isDir();

        // 获取文件图标
        SHFILEINFOW shFileInfo;
        DWORD_PTR result = SHGetFileInfoW(
            (LPCWSTR)fileInfo.absoluteFilePath().utf16(),
            0,
            &shFileInfo,
            sizeof(shFileInfo),
            SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES
        );

        if (result) {
            QPixmap pixmap = QPixmap::fromImage(QImage::fromHICON(shFileInfo.hIcon));
            if (!pixmap.isNull()) {
                desktopIcon.icon = QIcon(pixmap);
            }
            DestroyIcon(shFileInfo.hIcon);
        }
        else {
            // 使用默认图标
            QStyle* style = QApplication::style();
            if (fileInfo.isDir()) {
                desktopIcon.icon = style->standardIcon(QStyle::SP_DirIcon);
            }
            else {
                desktopIcon.icon = style->standardIcon(QStyle::SP_FileIcon);
            }
        }

        icons.append(desktopIcon);
    }

    return icons;
}
#endif